package com.example.springboot_test.easyexcel.handler;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.write.handler.AbstractRowWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.example.springboot_test.easyexcel.model.CellStyleModel;
import com.example.springboot_test.easyexcel.annotation.ReflectField;
import com.example.springboot_test.easyexcel.constant.StyleModelConstant;
import com.example.springboot_test.easyexcel.enums.BorderSideEnum;
import com.example.springboot_test.easyexcel.model.StyleModel;
import com.example.springboot_test.easyexcel.model.common.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 自定义单元格样式处理器
 * 支持字体样式、底纹信息、边框样式、对齐方式、自动换行、旋转文字、竖向文字、数据格式、自动收缩
 *
 * @author xudongmaster
 */
@Slf4j
public class CustomCellStyleHandler extends AbstractRowWriteHandler {
    /**
     * sheet页名称列表
     */
    private List<String> sheetNameList;
    /**
     * 样式信息
     */
    private Map<String, Map<Integer, List<CellStyleModel>>> sheetCellStyleMap = new HashMap<>();
    /**
     * styleModel和CellStyle映射map
     */
    private final Map<StyleModel, CellStyle> styleCellStyleMap = new HashMap<>();

    /**
     * 自定义样式适配器构造方法
     *
     * @param cellStyleList 样式信息
     */
    public CustomCellStyleHandler(List<CellStyleModel> cellStyleList) {
        if (CollUtil.isEmpty(cellStyleList)) {
            return;
        }
        Map<String, List<CellStyleModel>> allCellStyleModelMap = cellStyleList.stream().filter(x ->
                StrUtil.isNotBlank(x.getSheetName()) && x.getStyleModel() != null)
                .collect(Collectors.groupingBy(SheetModel::getSheetName));
        if (allCellStyleModelMap == null || CollUtil.isEmpty(allCellStyleModelMap.keySet())) {
            return;
        }
        sheetNameList = new ArrayList<>(allCellStyleModelMap.keySet());
        //为了方便筛选数据
        Map<Integer, List<CellStyleModel>> sheetCellStyleModelMap;
        for (String sheetName : sheetNameList) {
            sheetCellStyleModelMap = allCellStyleModelMap.get(sheetName).stream().collect(Collectors.groupingBy(SheetCellModel::getRowIndex));
            sheetCellStyleMap.put(sheetName, sheetCellStyleModelMap);
        }
    }

    @Override
    public void afterRowDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row
            , Integer relativeRowIndex, Boolean isHead) {
        //跳过表头
        if (isHead) {
            return;
        }
        Sheet sheet = writeSheetHolder.getSheet();
        //不需要添加样式，或者当前sheet页不需要添加样式
        if (sheetCellStyleMap == null || CollUtil.isEmpty(sheetCellStyleMap.keySet()) || !sheetNameList.contains(sheet.getSheetName())) {
            return;
        }
        Map<Integer, List<CellStyleModel>> rowCSMMap = sheetCellStyleMap.get(sheet.getSheetName());
        //获取当前行的样式信息
        List<CellStyleModel> rowCellStyleList = rowCSMMap.get(relativeRowIndex);
        //该行不需要设置样式
        if (CollUtil.isEmpty(rowCellStyleList)) {
            return;
        }
        Cell cell;
        for (CellStyleModel cellStyleModel : rowCellStyleList) {
            //列索引
            int colIndex = cellStyleModel.getColIndex();
            //边框样式
            cell = row.getCell(colIndex) == null ? row.createCell(colIndex) : row.getCell(colIndex);
            //样式不追加，并且CellStyle也存在
            if (!cellStyleModel.getStyleModel().isAppend()
                    && styleCellStyleMap.get(cellStyleModel.getStyleModel()) != null) {
                //样式优化，styleModel对象相同时，CellStyle对象也相同
                cell.setCellStyle(styleCellStyleMap.get(cellStyleModel.getStyleModel()));
            } else {
                //设置单元格样式
                setCellStyle(cellStyleModel, cell);
            }
        }
        //删除已添加的样式信息
        rowCSMMap.remove(relativeRowIndex);
    }

    /**
     * 给单元格设置样式
     *
     * @param cellStyleModel 样式信息
     * @param cell           单元格对象
     */
    private void setCellStyle(CellStyleModel cellStyleModel, Cell cell) {
        //优先从CellStyleMap取，没有再创建
        StyleModel styleModel = cellStyleModel.getStyleModel();
        XSSFCellStyle style = styleCellStyleMap.get(styleModel) == null
                ? (XSSFCellStyle) cell.getRow().getSheet().getWorkbook().createCellStyle() : (XSSFCellStyle) styleCellStyleMap.get(styleModel);
        // 克隆出一个 style
        style.cloneStyleFrom(cell.getCellStyle());
        //可追加的CellStyle对象不放入CellStyleMap中
        if (!styleModel.isAppend()) {
            styleCellStyleMap.put(styleModel, style);
        }
        List<Field> fieldList = FieldUtils.getFieldsListWithAnnotation(StyleModel.class, ReflectField.class);
        if (CollUtil.isNotEmpty(fieldList)) {
            //使用反射给CellStyle赋值
            for (Field field : fieldList) {
                field.setAccessible(true);
                String fieldName = field.getName();
                ReflectField reflectField = field.getAnnotation(ReflectField.class);
                String invokeMethodName = reflectField.invokeMethodName();
                Object fieldValue;
                try {
                    fieldValue = field.get(styleModel);
                } catch (IllegalAccessException e) {
                    log.error("获取StyleModel的{}属性值失败：", fieldName, e);
                    continue;
                }
                //当前字段没有赋值
                if (fieldValue == null) {
                    continue;
                }
                //数据格式(从String转化为DataFormat)
                if (StrUtil.equals(StyleModelConstant.ATTR_NAME_DATA_FORMAT, fieldName)) {
                    DataFormat dataFormat = cell.getRow().getSheet().getWorkbook().createDataFormat();
                    fieldValue = dataFormat.getFormat((String) fieldValue);
                }
                ReflectUtil.invoke(style, invokeMethodName, fieldValue);
            }
        }
        //设置底纹
        if (styleModel.getCellShadingModel() != null) {
            setCellShading(style, styleModel.getCellShadingModel());
        }
        //设置字体样式
        FontModel fontModel = styleModel.getFontModel();
        if (fontModel != null) {
            setFontStyle(cell, style, fontModel);
        }
        //设置边框样式
        Map<BorderSideEnum, BorderModel> borderModelMap = styleModel.getBorderModelMap();
        if (borderModelMap != null && borderModelMap.size() > 0) {
            setBorderStyle(style, borderModelMap);
        }
        cell.setCellStyle(style);
    }

    /**
     * 设置底纹信息
     *
     * @param style            单元格样式
     * @param cellShadingModel 底纹信息
     */
    private void setCellShading(XSSFCellStyle style, CellShadingModel cellShadingModel) {
        //背景颜色
        Object backgroundColor = cellShadingModel.getBackgroundColor();
        //前景色
        Object foregroundColor = cellShadingModel.getForegroundColor();
        //底纹样式
        FillPatternType fillPatternType = cellShadingModel.getFillPattern();
        fillPatternType = fillPatternType == null ? FillPatternType.SOLID_FOREGROUND : fillPatternType;
        //背景颜色和前景色不存在时，不设置底纹
        if (backgroundColor == null && foregroundColor == null) {
            style.setFillPattern(fillPatternType);
            return;
        }
        //设置背景颜色(背景色和前景色都存在的情况)
        if (backgroundColor != null && foregroundColor != null) {
            //使用IndexedColors定义的颜色
            if (backgroundColor instanceof IndexedColors) {
                style.setFillBackgroundColor(((IndexedColors) backgroundColor).getIndex());
            }
            //使用自定义的RGB颜色
            else if (backgroundColor instanceof XSSFColor) {
                style.setFillBackgroundColor((XSSFColor) backgroundColor);
            }
        }
        //前景色不存在，设置背景色(前景色存在设置前景色)
        foregroundColor = foregroundColor == null ? backgroundColor : foregroundColor;
        //使用IndexedColors定义的颜色
        if (foregroundColor instanceof IndexedColors) {
            style.setFillForegroundColor(((IndexedColors) foregroundColor).getIndex());
        }
        //使用自定义的RGB颜色
        else if (foregroundColor instanceof XSSFColor) {
            style.setFillForegroundColor((XSSFColor) foregroundColor);
        }
        //设置底纹样式
        style.setFillPattern(fillPatternType);
    }

    /**
     * 设置字体样式
     *
     * @param cell      单元格对象
     * @param style     单元格样式
     * @param fontModel 字体信息
     */
    private void setFontStyle(Cell cell, XSSFCellStyle style, FontModel fontModel) {
        XSSFFont font;
        //样式存在字体对象时，使用原有的字体对象
        if (style.getFontIndex() != 0) {
            font = style.getFont();
        }
        //样式不存在字体对象时，创建字体对象
        else {
            font = (XSSFFont) cell.getRow().getSheet().getWorkbook().createFont();
            //默认字体为宋体
            font.setFontName("宋体");
        }
        List<Field> fieldList = FieldUtils.getFieldsListWithAnnotation(FontModel.class, ReflectField.class);
        if (CollUtil.isNotEmpty(fieldList)) {
            //使用反射给CellStyle赋值
            for (Field field : fieldList) {
                field.setAccessible(true);
                String fieldName = field.getName();
                ReflectField reflectField = field.getAnnotation(ReflectField.class);
                String invokeMethodName = reflectField.invokeMethodName();
                Object fieldValue;
                try {
                    fieldValue = field.get(fontModel);
                } catch (IllegalAccessException e) {
                    log.error("获取FontModel的{}属性值失败：", fieldName, e);
                    continue;
                }
                //当前字段没有赋值
                if (fieldValue == null) {
                    continue;
                }
                //字段值为IndexedColors时，字段值取索引值
                if (fieldValue instanceof IndexedColors) {
                    fieldValue = ((IndexedColors) fieldValue).getIndex();
                }
                ReflectUtil.invoke(font, invokeMethodName, fieldValue);
            }
        }
        style.setFont(font);
    }

    /**
     * 设置边框样式
     *
     * @param style          单元格样式
     * @param borderModelMap 边框信息map
     */
    private void setBorderStyle(XSSFCellStyle style, Map<BorderSideEnum, BorderModel> borderModelMap) {
        //设置边框线条类型和边框线条颜色
        for (Map.Entry<BorderSideEnum, BorderModel> borderModelEntry : borderModelMap.entrySet()) {
            BorderModel borderModel = borderModelEntry.getValue();
            BorderSideEnum borderSideEnum = borderModelEntry.getKey();
            //设置边框线条类型
            BorderStyle borderStyle = borderModel.getBorderStyle();
            if (borderStyle != null) {
                ReflectUtil.invoke(style, borderSideEnum.getBorderStyleMethodName(), borderStyle);
            }
            //设置边框线条颜色
            Object borderColor = borderModel.getBorderColor();
            if (borderColor != null) {
                //使用IndexedColors定义的颜色，使用索引值
                if (borderColor instanceof IndexedColors) {
                    borderColor = ((IndexedColors) borderColor).getIndex();
                }
                ReflectUtil.invoke(style, borderSideEnum.getBorderColorMethodName(), borderColor);
            }
        }
    }
}
